﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Caching;
using System.Web.Security;


using System.Data;
using System.Text.RegularExpressions;

using CooWork.Services;
using Coowork.Data.Mapping;

namespace CooWork.Models
{
    public static class CacheSet
    {

        public static bool EC(string action, string controller,int authrole,int cid)
        {
            string taskCacheStr = string.Format("EC_{0}_{1}_{2}", action, controller, authrole);

            var obj = MemoryCache.Default.Get(taskCacheStr);

            if (obj != null)
            {
                return (bool)obj;
            }
            
            CooWorkEntities ctx = new CooWorkEntities();
            var ua = ctx.UserAuths.Any(x => x.AuthAction.ToLower() == action.ToLower() && x.AuthController.ToLower() == controller.ToLower() && x.AuthRole == authrole && x.cid == 0);
                        
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);

            if (ua)
            {
                MemoryCache.Default.Add(new CacheItem(taskCacheStr, true), policy);
                return true;
            }

            MemoryCache.Default.Add(new CacheItem(taskCacheStr, false), policy);
            return false;
        }


        public static string u2n2(string s)
        {
            int companyid = UserService.UcId();
            string ret = string.Empty;
            Dictionary<System.Guid, string> dgs = UserCacheCompany2(companyid, false);
            dgs.TryGetValue(new Guid(s), out ret);
            return ret;
        }

        public static string U2N(System.Guid? gid)
        {
            if (!gid.HasValue) return "";
            int companyid = UserService.UcId();
            string ret = string.Empty;
            Dictionary<System.Guid, string> dgs = UserCacheCompany(companyid,false);
            dgs.TryGetValue(gid.Value, out ret);
            return ret;
        }

        public static string U2N(System.Guid? gid,bool reset)
        {
            if (!gid.HasValue) return "";
            int companyid = UserService.UcId();
            string ret = string.Empty;
            Dictionary<System.Guid, string> dgs = UserCacheCompany(companyid, reset);
            dgs.TryGetValue(gid.Value, out ret);
            return ret;
        }        


        public static string U2N(int companyid, System.Guid? gid)
        {
            if (!gid.HasValue) return "";
            string ret = string.Empty;
            Dictionary<System.Guid, string> dgs = UserCacheCompany(companyid,false);
            dgs.TryGetValue(gid.Value, out ret);
            return ret;
        }

        public static string U2N(int companyid, System.Guid? gid,bool reset)
        {
            if (!gid.HasValue) return "";
            string ret = string.Empty;
            Dictionary<System.Guid, string> dgs = UserCacheCompany(companyid, reset);
            dgs.TryGetValue(gid.Value, out ret);
            return ret;
        }


        public static Dictionary<System.Guid, string> UserCacheCompany(int companyid,bool reset)
        {

            string key = "UserCache_" + companyid;
            var obj = MemoryCache.Default.Get(key);

            if (obj == null||reset)
            {
                Dictionary<System.Guid, string> userCache = new Dictionary<System.Guid, string>();            
                DataTable dt = DataProvider.GetDataTable("select * from aspnet_Users where cid=" + companyid);
                foreach (DataRow dr in dt.Rows)
                {
                    userCache.Add((System.Guid)dr["UserId"], dr["ActualName"].ToString());
                } 

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                if (reset) MemoryCache.Default.Remove(key);
                MemoryCache.Default.Add(new CacheItem(key, userCache), policy);       

                //   return null;
            }
            return (MemoryCache.Default[key] as Dictionary<System.Guid, string>);
        }

        /// <summary>
        /// 仅限登录名
        /// </summary>
        /// <param name="companyid"></param>
        /// <param name="reset"></param>
        /// <returns></returns>
        public static Dictionary<System.Guid, string> UserCacheCompany2(int companyid, bool reset)
        {

            string key = "UserCache2_" + companyid;
            var obj = MemoryCache.Default.Get(key);

            if (obj == null || reset)
            {
                Dictionary<System.Guid, string> userCache = new Dictionary<System.Guid, string>();
                DataTable dt = DataProvider.GetDataTable("select * from aspnet_Users where cid=" + companyid);
                foreach (DataRow dr in dt.Rows)
                {
                    userCache.Add((System.Guid)dr["UserId"], dr["username"].ToString());
                }

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                if (reset) MemoryCache.Default.Remove(key);
                MemoryCache.Default.Add(new CacheItem(key, userCache), policy);

                //   return null;
            }
            return (MemoryCache.Default[key] as Dictionary<System.Guid, string>);
        }




        public static string _cdepartment(Department d)
        {
            var ret = string.Empty;
            ret += "," + d.ID;
            foreach (Department dd in d.Department1)
            {
                ret += "," + _cdepartment(dd);            
   
            }
            return ret.Trim(',');
        }



        public static string DepartmentUsers(int? departmentId,bool reset)
        {
            var ret = string.Empty;

            string key = "DepartmentUsers_" + departmentId.ToString();
            var obj = MemoryCache.Default.Get(key);

            if (obj == null||reset)
            {
                CooWorkEntities ctx = new CooWorkEntities();
                var cid = UserService.UcId();
                var d = ctx.Departments.Where(x => x.cid == cid).Where(x=>x.ID==departmentId).SingleOrDefault();
                string sql = "select  * from [CooWork].[dbo].[aspnet_Users] where cid={0} and did in ({1})";
                sql = string.Format(sql,
                                UserService.UcId(),
                                _cdepartment(d));

                DataTable dt = DataProvider.GetDataTable(sql);
                foreach (DataRow dr in dt.Rows)
                {
                    ret += ","+dr["UserId"];
                }
                ret = ret.Trim(',');

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                if (reset) MemoryCache.Default.Remove(key);
                MemoryCache.Default.Add(new CacheItem(key, ret), policy);

                //   return null;
            }
            return (MemoryCache.Default[key] as string);
        }


















        public static Dictionary<System.Guid, string> UserCache
        {
            get
            {
                var obj = MemoryCache.Default.Get("UserCache");
                
                if (obj != null)
                {
                    return obj as Dictionary<System.Guid, string>;
                }
                else
                {
                   var userlist =  Membership.GetAllUsers();
                   Dictionary<System.Guid, string> userCache = new Dictionary<System.Guid, string>();
                   foreach (MembershipUser u in userlist)
                   {                       
                     userCache.Add((System.Guid)u.ProviderUserKey,u.UserName);
                   }
      
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                    MemoryCache.Default.Add(new CacheItem("UserCache", userCache), policy);
                    return userCache;

                    //   return null;
                }

            }


        }


        public static Dictionary<int, string> severityCache
        {

            get
            {
                var obj = MemoryCache.Default.Get("severityCache");
                if (obj != null)
                {
                    return obj as Dictionary<int, string>;
                }
                else
                {
                    CooWorkEntities ctx = new CooWorkEntities();
                    Dictionary<int, string> severityCache = new Dictionary<int, string>();
                    var severityList = ctx.CooEnums.Where(a => a.c == "severity").Select(a => new
                    {
                        a.eid,
                        a.ename
                    }).ToList();
                    foreach (var item in severityList)
                    {
                        severityCache.Add(item.eid.Value, item.ename);
                    }
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                    MemoryCache.Default.Add(new CacheItem("severityCache", severityCache), policy);
                    return severityCache;
                    //   return null;
                }

            }
        }
        


        public static Dictionary<int, string> priorityCache
        {

            get
            {
                var obj = MemoryCache.Default.Get("priorityCache");
                if (obj != null)
                {
                    return obj as Dictionary<int, string>;
                }
                else
                {
                    CooWorkEntities ctx = new CooWorkEntities();
                    Dictionary<int, string> priorityCache = new Dictionary<int, string>();
                    var priorityList = ctx.CooEnums.Where(a => a.c == "priority").Select(a => new
                    {
                        a.eid,
                        a.ename
                    }).ToList();
                    foreach (var item in priorityList)
                    {
                        priorityCache.Add(item.eid.Value, item.ename);
                    }
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                    MemoryCache.Default.Add(new CacheItem("priorityCache", priorityCache), policy);
                    return priorityCache;
                    //   return null;
                }

            }
        }



        public static string Stats2N(int? id)
        {
            if (!id.HasValue) return "";
            string ret = string.Empty;
            Dictionary<int, string> dgs = StatusCache;
            dgs.TryGetValue(id.Value, out ret);
            return ret;
        }

        public static string Priority2N(int? id)
        {
            if (!id.HasValue) return "";
            string ret = string.Empty;
            Dictionary<int, string> dgs = priorityCache;
            dgs.TryGetValue(id.Value, out ret);
            return ret;
        }

        public static string Severity2N(int? id)
        {
            if (!id.HasValue) return "";
            string ret = string.Empty;
            Dictionary<int, string> dgs = severityCache;
            dgs.TryGetValue(id.Value, out ret);
            return ret;
        }


        public static Dictionary<int, string> StatusCache
        {

            get
            {
                var obj = MemoryCache.Default.Get("StatusCache");
                if (obj != null)
                {
                    return obj as Dictionary<int, string>;
                }
                else
                {
                    CooWorkEntities ctx = new CooWorkEntities();
                    Dictionary<int, string> StatusCache = new Dictionary<int, string>();
                    var StatusList = ctx.CooEnums.Where(a=>a.c=="StatusId").Select(a => new
                                {
                                    a.eid,
                                    a.ename
                                }).ToList();
                    foreach (var item in StatusList)
                    {
                        StatusCache.Add(item.eid.Value, item.ename);
                    }
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                    MemoryCache.Default.Add(new CacheItem("StatusCache", StatusCache), policy);
                    return StatusCache;
                    //   return null;
                }

            }
        }



        public static string DorU2N(string s)
        {
            if (s.Contains("department"))
            {
                var id= Regex.Match(s, @"_(\d+)").Groups[1].Value;

                return D2N(int.Parse(id));               
            }
            else
            {
                return U2N(new Guid(s));
            }

        }





        public static string D2N(int departmentId)
        {
            string ret = string.Empty;
            Dictionary<int, string> dgs = DepartmentCache;
            dgs.TryGetValue(departmentId, out ret);
            return ret;
        }




        public static Dictionary<int, string> DepartmentCache
        {
            get {
                 var obj = MemoryCache.Default.Get("DepartmentCache");
               

                if (obj != null)
                {
                    return obj as Dictionary<int, string>;
                }
                else
                {
                    CooWorkEntities ctx = new CooWorkEntities();
                    Dictionary<int, string> departmentCache=new Dictionary<int,string>();
                    var departmentlist = ctx
                                         .Departments
                                         .Select(a =>
                                             new
                                             {
                                                 a.ID,
                                                 a.DepartmentName
                                             }
                                             ).ToList();
                    departmentCache.Add(0, "Not set");
                    foreach (var item in departmentlist)
                    {
                        departmentCache.Add(item.ID, item.DepartmentName);
                    }
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30.0);
                    MemoryCache.Default.Add(new CacheItem("DepartmentCache", departmentCache), policy);

                    return departmentCache;
                  
                 //   return null;
                }
            
            }
            
        }


   

       
       


    }
}